package com.wb.mas.ui.auth;

import android.app.Application;
import android.net.Uri;
import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;

import com.blankj.utilcode.util.SPUtils;
import com.wb.mas.R;
import com.wb.mas.app.Constants;
import com.wb.mas.app.SPKeys;
import com.wb.mas.app.UUidUtils;
import com.wb.mas.data.DemoRepository;
import com.wb.mas.entity.FaceCompareResponse;
import com.wb.mas.entity.IdentityEntity;
import com.wb.mas.entity.ImageInfoEntity;
import com.wb.mas.entity.RootApiBean;
import com.wb.mas.entity.SubmitedAuthResponse;
import com.wb.mas.entity.UploadImageResponse;
import com.wb.mas.utils.response.ResultException;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;
import me.goldze.mvvmhabit.utils.KLog;
import me.goldze.mvvmhabit.utils.StringUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;

public class AuthIdViewModel extends AuthBaseViewModel {
    private static final String TAG = AuthIdViewModel.class.getSimpleName();

    //身份证姓名
    public ObservableField<String> idCardName = new ObservableField<>("");
    //身份证 号
    public ObservableField<String> idCardNum = new ObservableField<>("");
    //生日
    public ObservableField<String> idCardBirthday = new ObservableField<>("");

    public ObservableField<SubmitedAuthResponse.DataBean.IdentityBean.IdentityImagesBean> idCardPositiveBean = new ObservableField<>();
    public ObservableField<SubmitedAuthResponse.DataBean.IdentityBean.IdentityImagesBean> idCardNegativeBean = new ObservableField<>();


    public boolean existFirstPhoto = false;
    public boolean existSecondPhoto = false;


    public UiChangeEvent uc = new UiChangeEvent();
    private String imgUrl1;
    private String imgUrl2;
    private ImageInfoEntity imageInfo1;
    private ImageInfoEntity imageInfo2;

    public void initToolBar() {
        setTitleText(getString(R.string.auth_page_title_name));
    }


    public class UiChangeEvent {
        public SingleLiveEvent takePhoto1Event = new SingleLiveEvent();
        public SingleLiveEvent takePhoto2Event = new SingleLiveEvent();
        public SingleLiveEvent birthdayClickEvent = new SingleLiveEvent();
    }


    public AuthIdViewModel(@NonNull Application application, DemoRepository model) {
        super(application, model);
    }

    @Override
    public void onCreate() {
        super.onCreate();

        init();

        getSubmitedInfo(Constants.AUTH_PAGE_CODE_IDENTITY_COD);
    }

    private void init() {


    }


    @Override
    protected void onSubmittedResponse(SubmitedAuthResponse response) {
        super.onSubmittedResponse(response);

        if (response != null && response.getData() != null && response.getData().getIdentity() != null) {


            SubmitedAuthResponse.DataBean.IdentityBean identity = response.getData().getIdentity();

            idCardName.set(identity.getRealName());
            idCardNum.set(identity.getIdentityCardNum());
            idCardBirthday.set(identity.getBirthday());

            List<SubmitedAuthResponse.DataBean.IdentityBean.IdentityImagesBean> identityImages = response.getData().getIdentity().getIdentityImages();
            if (identityImages != null && identityImages.size() > 0) {
                for (int i = 0; i < identityImages.size(); i++) {
                    SubmitedAuthResponse.DataBean.IdentityBean.IdentityImagesBean identityImagesBean = identityImages.get(i);
                    if (Constants.FILE_TYPE_OF_1.equals(identityImagesBean.getFileType() + "")) {

                        imgUrl1 = identityImagesBean.getImagePath();
                        idCardPositiveBean.set(identityImagesBean);
                        imageInfo1 = new ImageInfoEntity();
                        imageInfo1.setImageUrl(identityImagesBean.getImageUrl());
                        imageInfo1.setImagePath(identityImagesBean.getImagePath());
                        imageInfo1.setImageName(identityImagesBean.getImageName());
                        imageInfo1.setFileType(identityImagesBean.getFileType());
                    } else if (Constants.FILE_TYPE_OF_2.equals(identityImagesBean.getFileType() + "")) {

                        imageInfo2 = new ImageInfoEntity();
                        imageInfo2.setImageUrl(identityImagesBean.getImageUrl());
                        imageInfo2.setImagePath(identityImagesBean.getImagePath());
                        imageInfo2.setImageName(identityImagesBean.getImageName());
                        imageInfo2.setFileType(identityImagesBean.getFileType());

                        imgUrl2 = identityImagesBean.getImagePath();
                        idCardNegativeBean.set(identityImagesBean);
                    }

                }

            }


        }

    }

    public BindingCommand clickUploadPositiveCover = new BindingCommand(new BindingAction() {
        @Override
        public void call() {

            KLog.i(TAG, "clickUploadPositiveCover");

            uc.takePhoto1Event.setValue(new Object());


        }
    });

    public BindingCommand clickUploadNegativeCover = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            KLog.i(TAG, "clickUploadNegativeCover");

            uc.takePhoto2Event.setValue(new Object());

        }
    });

    public BindingCommand birthdayClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            KLog.i(TAG, "clickUploadNegativeCover");

            uc.birthdayClickEvent.setValue(new Object());

        }
    });


    public BindingCommand onClickNextStep = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            setTitleText(getString(R.string.auth_page_title_name));

            if (TextUtils.isEmpty(imgUrl1) || TextUtils.isEmpty(imgUrl2)) {
                ToastUtils.showShort(getApplication().getResources().getString(R.string.auth_please_upload_photo));
                return;
            }

            if (StringUtils.isEmpty(idCardName.get())) {

                ToastUtils.showShort(getApplication().getResources().getString(R.string.auth_please_input_card_name));
                return;
            }

            if (StringUtils.isEmpty(idCardNum.get())) {

                ToastUtils.showShort(getApplication().getResources().getString(R.string.auth_please_input_card_num));
                return;
            }


            if (!StringUtils.isEmpty(idCardNum.get()) && idCardNum.get().length() != 16) {

                ToastUtils.showShort(getApplication().getResources().getString(R.string.auth_id_card_num_length_illegal));
                return;
            }

            if (StringUtils.isEmpty(idCardBirthday.get())) {

                ToastUtils.showShort(getApplication().getResources().getString(R.string.auth_please_input_card_birthday));
                return;
            }

            verifyTwoPhoto();


        }
    });


    /**
     * {
     * "secondImagePath": "\/data1\/pic\/APP\/2019-04\/23\/file\/3aOKxIAY.jpg",    //手持身份证照片相对路径
     * "firstImagePath": "\/data1\/pic\/APP\/2019-04\/23\/file\/kvgEpbQi.jpg",  //身份证相对
     * "channel": "1",
     * "commonParam":  //公参
     * "userUuid": "20190423950"   //用户的uuid 根据不同的情况传不同的uuid
     * }
     */
    private void verifyTwoPhoto() {

        showDialog();
        if (TextUtils.isEmpty(imgUrl1) || TextUtils.isEmpty(imgUrl2)) {
            ToastUtils.showShort(getString(R.string.auth_id_please_take_photo));
            return;
        }
        Map<String, Object> param = new HashMap<>();
        param.put("firstImagePath", imgUrl1);
        param.put("secondImagePath", imgUrl2);
        model.faceCompare(param)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<FaceCompareResponse>() {
                    @Override
                    public void accept(FaceCompareResponse response) throws Exception {
                        dismissDialog();
                        if (response == null || response.getStatus() != 200 || response.getData() == null || !response.getData().isCompareStatus()) {

                            ToastUtils.showShort(response.getMessage());

                            return;
                        }

                        doUploadIdInfo(response.getData());

                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        dismissDialog();
                        KLog.e("error:" + throwable.getMessage());
                        if (throwable instanceof ResultException) {
                            ToastUtils.showShort(throwable.getMessage());

                        }
                    }
                });


    }


    /**
     * {
     * "pass": 1,     //对比图片的返回
     * "city": "KABUPATEN KLATEN",
     * "realName": "YOHANES PRASETYO",
     * "userUuid": "20190423953",  //用户uuid 根据提交类型不同不同
     * "province": "JAWA TENGAH",
     * "imageInfoParams": [       //身份图片信息上传的2个信息
     * {
     * "fileType": 1,
     * "imageName": "file",
     * "imagePath": "\/data1\/pic\/APP\/2019-04\/23\/file\/D21P6rsI.jpg",
     * "imageUrl": "http:\/\/47.92.143.84\/pic\/APP\/2019-04\/23\/file\/D21P6rsI.jpg"
     * },
     * {
     * "fileType": 2,
     * "imageName": "file",
     * "imagePath": "\/data1\/pic\/APP\/2019-04\/23\/file\/1J67ZHNu.jpg",
     * "imageUrl": "http:\/\/47.92.143.84\/pic\/APP\/2019-04\/23\/file\/1J67ZHNu.jpg"
     * }
     * ],
     * "birthday": "1993.08.08",
     * "commonParam": 公参
     * "authPageCode": "identity_code",   //身份认证信息的
     * "maritalStatus": "BELUM KAWIN",
     * "religion": "KRISTEN",
     * "district": "KEBONARUM",
     * "identityCardNum": "3310070808930003",
     * "channel": "1",    //渠道
     * “isInformationWrong”:1   //如果是资料退回再次上传的 传1  要不是不传
     * }
     */
    private void doUploadIdInfo(FaceCompareResponse.DataBean compareData) {
        showDialog();
        Map<String, Object> param = new HashMap<>();
        if (SPUtils.getInstance().getBoolean(SPKeys.SP_ISBACK)) {
            param.put("isInformationWrong", "1");

        }
        param.put("pass", compareData.getPass());
        param.put("realName", idCardName.get());
        param.put("birthday", idCardBirthday.get());
        param.put("authPageCode", Constants.AUTH_PAGE_CODE_IDENTITY_COD);
        param.put("identityCardNum", idCardNum.get());

        List<SubmitedAuthResponse.DataBean.IdentityBean.IdentityImagesBean> imgList = new ArrayList<>();

        SubmitedAuthResponse.DataBean.IdentityBean.IdentityImagesBean bean1 = new SubmitedAuthResponse.DataBean.IdentityBean.IdentityImagesBean();
        bean1.setFileType(Integer.parseInt(Constants.FILE_TYPE_OF_1));
        bean1.setImageUrl(imageInfo1.getImageUrl());
        bean1.setImagePath(imageInfo1.getImagePath());
        bean1.setImageName(imageInfo1.getImageName());
        imgList.add(bean1);

        SubmitedAuthResponse.DataBean.IdentityBean.IdentityImagesBean bean2 = new SubmitedAuthResponse.DataBean.IdentityBean.IdentityImagesBean();
        bean2.setFileType(Integer.parseInt(Constants.FILE_TYPE_OF_2));
        bean2.setImageUrl(imageInfo2.getImageUrl());
        bean2.setImagePath(imageInfo2.getImagePath());
        bean2.setImageName(imageInfo2.getImageName());
        imgList.add(bean2);

        param.put("imageInfoParams", imgList);
        model.updateOrSaveUser(param)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<RootApiBean>() {
                    @Override
                    public void accept(RootApiBean response) throws Exception {
                        dismissDialog();
                        if (response == null || response.getStatus() != 200 || response.getData() == null) {
                            if (response != null && !TextUtils.isEmpty(response.getMessage())) {
                                ToastUtils.showShort(response.getMessage());
                            }
                            return;

                        }

                        AuthJumpManager.jumpToNextPage(Constants.AUTH_PAGE_CODE_IDENTITY_COD);
                        finish();

                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        dismissDialog();
                        KLog.e("error:" + throwable.getMessage());
                        if (throwable instanceof ResultException) {
                            ToastUtils.showShort(throwable.getMessage());

                        }
                    }
                });


    }


    public void doUploadImg(Uri imageUri, File imageFile, final String fileType) {
        showDialog();
        Map<String, Object> params = new HashMap<>();
        params.put("userUuid", UUidUtils.getUUid());
        params.put("fileType", fileType);

        KLog.i("upload img start");


        model.uploadImage(params, imageFile)
//        model.uploadImage(params, new File(imageUri.getPath()))
//        model.uploadImage(params, new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),"JPEG_20190508_004210_.jpg"))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<UploadImageResponse>() {
                    @Override
                    public void accept(UploadImageResponse uploadImageResponse) throws Exception {

                        dismissDialog();
                        if (uploadImageResponse != null && uploadImageResponse.getData() != null && uploadImageResponse.getData().getImageInfo() != null) {
                            ImageInfoEntity imageInfo = uploadImageResponse.getData().getImageInfo();
                            if (Constants.FILE_TYPE_OF_1.equals(imageInfo.getFileType() + "")) {

                                imageInfo1 = imageInfo;
                                imgUrl1 = imageInfo.getImagePath();
                                KLog.i(TAG, "imgUrl1:" + imgUrl1);
                            } else if (Constants.FILE_TYPE_OF_2.equals(imageInfo.getFileType() + "")) {

                                imageInfo2 = imageInfo;
                                imgUrl2 = imageInfo.getImagePath();
                                KLog.i(TAG, "imgUrl2:" + imgUrl2);
                            }
                        }


                        if (uploadImageResponse != null && uploadImageResponse.getData() != null && uploadImageResponse.getData().getIdentity() != null) {
                            uploadImageResponse.getData().getImageInfo();
                            IdentityEntity identity = uploadImageResponse.getData().getIdentity();


                            if (!TextUtils.isEmpty(identity.getRealName())) {
                                idCardName.set(identity.getRealName());

                            }
                            if (!TextUtils.isEmpty(identity.getIdentityCardNum())) {

                                idCardNum.set(identity.getIdentityCardNum());
                            }
                            if (!TextUtils.isEmpty(identity.getBirthday())) {

                                idCardBirthday.set(identity.getBirthday());
                            }

                        }


                        KLog.i("upload img suc");
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        dismissDialog();
                        KLog.e("upload fail:" + throwable.getMessage());
                        if (Constants.FILE_TYPE_OF_1.equals(fileType)) {
                            idCardPositiveBean.set(null);

                        } else if (Constants.FILE_TYPE_OF_2.equals(fileType)) {
                            idCardNegativeBean.set(null);
                        }

                        if (throwable instanceof ResultException) {
                            ToastUtils.showShort(throwable.getMessage());

                        }
                    }
                });
    }


}
